﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DevExpress.Xpo;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RemoteImaging.LicensePlate
{
    public class CarBlacklistImporter
    {
        private readonly IMessageBoxService _messageBoxService;
        private readonly IVisualStateManager _visualStateManager;
        private OpenFileDialog openExcelDialog = null;
        public CarBlacklistImporter(IMessageBoxService messageBoxService,
                                    IVisualStateManager visualStateManager)
        {
            _visualStateManager = visualStateManager;
            _messageBoxService = messageBoxService;

            openExcelDialog = new OpenFileDialog();
            openExcelDialog.Filter = "Excel 文件|*.xls";
        }

        public async void InputAndUpdate(bool add)
        {

            var dr = openExcelDialog.ShowDialog();
            if (dr == DialogResult.OK)
            {
                try
                {
                    _visualStateManager.IsBusy = true;
                    var imports = await GetImportsAsync(openExcelDialog.FileName);
                    if (imports.Count() == 0)
                    {
                        _messageBoxService.ShowError("导入记录为空，请确保文件格式正确！");
                        return;
                    }

                    if (!add)
                    {
                        dr = _messageBoxService.ShowQuestion("确实要删除导入的记录吗？");
                        if (dr != DialogResult.Yes) return;
                    }

                    var q = from s in imports
                            select s;
                    await UpdateDbAsync(add, q.ToList());
                    _visualStateManager.IsBusy = false;
                    if (_messageBoxService.ShowQuestion("导入成功，要查看最新的黑名单吗？") == DialogResult.Yes)
                    {
                        using (var form = new LicensePlate.FormSuspectCarManager())
                        {
                            form.ShowDialog();
                        }
                    }

                }
                catch (Exception ex)
                {
                    _messageBoxService.ShowError("无法导入选定的文件，请检查文件后重试。");
                    _visualStateManager.IsBusy = false;
                }
                finally
                {
                    //_visualStateManager.IsBusy = false;
                }
            }

        }

        private async Task<SuspectCarInfoDto[]> GetImportsAsync(string fileName)
        {
            var ep = new FileHelpers.DataLink.ExcelStorage(typeof(SuspectCarInfoDto));
            ep.FileName = openExcelDialog.FileName;

            var carsToImport = await TaskEx.Run(() => (SuspectCarInfoDto[])ep.ExtractRecords());
            return carsToImport;
        }

        private static async Task UpdateDbAsync(bool add, IEnumerable<SuspectCarInfoDto> imports)
        {
            await TaskEx.Run(() =>
            {
                var uow = new UnitOfWork();
                foreach (var reportedCarInfo in imports)
                {
                    if (add)
                        AddOrUpdate(reportedCarInfo, uow);
                    else
                        Delete(reportedCarInfo.LicenseNumber, uow);
                }
                uow.CommitChanges();
            });

        }
        private static void AddOrUpdate(SuspectCarInfoDto newRecord, Session session)
        {
            var found = LicensePlate.Helper.FindReportedCarInfoBy(newRecord.LicenseNumber, session);
            if (found != null)
            {
                found.CopyFrom(newRecord);
                found.Save();
            }
            else
            {
                var rci = new ReportedCarInfo(session);
                rci.CarFrameNumber = newRecord.CarFrameNumber;
                rci.CarType = newRecord.CarType;
                rci.CaseNumber = newRecord.CaseNumber;
                rci.Color = newRecord.Color;
                rci.EngineNumber = newRecord.EngineNumber;
                rci.LicenseNumber = newRecord.LicenseNumber;
                rci.Url = newRecord.Url;
                rci.Save();

                //suspectCars.Add(newRecord);
            }
        }

        private static void Delete(string licenseNumber, Session session)
        {
            var found = LicensePlate.Helper.FindReportedCarInfoBy(licenseNumber, session);
            if (found != null)
            {
                found.Delete();
            }

        }


    }
}
